<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>slide</title>
	<style>
		.slide{margin: 100px auto;width: 320px;height: 480px;text-align: center;position: relative;}
 		.slide #img{height: 100%;width: 100%;}
 		.dot{position: absolute;background-color: rgba(0, 0, 0, 0.5);bottom: 0;left: 0;height: 20px;width: 100%;padding: 4px 0;line-height: 20px;}
 		.dot span{display: inline-block; width: 12px;height: 12px;background-color: snow;border-radius: 50%;} 
 		.dot .active{background-color: #e00;}
 		.prev,.next{position: absolute;top:205px;height: 70px;width: 70px;}
 		.prev{left: 5px;}
 		.next{right: 5px;}
	</style>
</head>
<body>

	<div class="slide">
		<img src="images/1.jpg" alt="" id="img">
		<img src="images/prev.png" alt="" class="prev" id="prev">
		<img src="images/next.png" alt="" class="next" id="next">
		<div class="dot" id="dot"></div>
	</div>


	<script>
		var spans = document.getElementsByTagName('span');
		var img   = document.getElementById('img');
		var dot   = document.getElementById('dot');
		var prev  = document.getElementById('prev');
		var next  = document.getElementById('next');
		var i 	  = 0;
		
		var imgArray  = ['1.jpg','2.jpg','3.jpg','3.png'];
		var imgLength = imgArray.length;

		/*动态添加span*/
		var str='';
		for(var k = 1;k <= imgLength;k++){
			if(k == 1){
				str += '<span class="active" id="' + k +'"></span> ';
			}else{
				str += '<span id="' + k +'"></span> ';
			}
		}
		//console.log(str);
		dot.innerHTML = str;

		function restartInterval(){
			interval = setInterval(function(){
				if(i == imgLength){
					i = 0;
				}
				for(var a =0;a < spans.length;a++){
					spans[a].classList.remove('active');//清除所有span中的active类
				}
				document.getElementById(i+1).classList.add('active');//为当前span添加active类

				img.src = './images/' + imgArray[i++];

			},1000);
		}	
		restartInterval();

		/*往前翻一张*/
		prev.onclick = function(){
			clearInterval(interval); //中止定时器

			if(i == 0){
				i = imgLength;
			}

			for(var a =0;a < spans.length;a++){
					spans[a].classList.remove('active');//清除所有span中的active类
				}
			document.getElementById(i).classList.add('active');//为当前span添加active类

			img.src = './images/' + imgArray[--i];

			restartInterval(); //重启定时器
		}

		/*往后翻一张*/
		next.onclick = function(){
			clearInterval(interval);

			if(i == imgLength-1){
				i = -1;
			}

			for(var a =0;a < spans.length;a++){
					spans[a].classList.remove('active');//清除所有span中的active类
				}
			document.getElementById(i+2).classList.add('active');//为当前span添加active类

			img.src = './images/' + imgArray[++i];

			restartInterval();
		}

	</script>
</body>
</html>